<template>
    <div class="role_form_container">
        <el-form ref="roleForm" :rules="rules" :model="formData" label-width="100px">
            <el-form-item label="角色编码" prop="code">
                <el-input v-model="formData.code" autocomplete="off" placeholder="请输入角色编码"></el-input>
            </el-form-item>
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="formData.name" autocomplete="off" placeholder="请输入角色名称"></el-input>
            </el-form-item>
            <el-form-item label="账户绑定" prop="role_sid" v-if="formData.sid !== 'admin'">
                <el-select v-model="formData.user_sid_list" placeholder="请选择账户" multiple clearable filterable
                           style="width: calc(100% - 28px);">
                    <el-option v-for="(item, index) in userList" :key="index"
                               :label="item.name" :value="item.sid" />
                </el-select>
                <el-button type="primary" size="mini" icon="el-icon-refresh"
                           @click="initUserList()" />
            </el-form-item>
            <el-form-item label="功能权限" prop="value">
                <vTreeEdit ref="roleTree" :options="treeOptions" :treeData="resourceZTreeData"
                           @event="handleTreeEvent" style="max-height: 400px;overflow-y: auto;" />
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import sysResourceApi from "@common/api/system/sysResourceApi";

export default {
    name: "RoleForm",
    props: {
        propsData: {
            type: Object,
            default() {
                return {
                    init: true,
                };
            },
        },
    },
    data() {
        return {
            userList: [],
            resourceZTreeData: [],
            leafResourceList: [],
            selectTreeData: [],
            treeOptions: {
                ref: "checkTree",
                showCheckbox: true, //节点是否可被选择
                indent: 26, //相邻级节点间的水平缩进，单位为像素
                draggable: false, //是否开启拖拽节点功能
            },
            rules: {
                code: [
                    { required: true, message: '请输入角色编码', trigger: 'blur' },
                    { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,32}$/, message: '最大 32 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符' }
                ],
                name: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,32}$/, message: '最大 32 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符' }
                ],
            },
            formData: {},
        };
    },
    watch: {
        propsData: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        init() {
            const _this = this;
            if (_this.propsData.init) {
                return;
            }
            _this.initUserList();
            _this.initResourceTree();
            if (_this.$refs.roleForm) {
                _this.$refs.roleForm.clearValidate();
            }
            _this.formData = $.extend({}, _this.propsData.row);
        },
        initUserList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindSysUsers, {
                nopage: '1',
            }).then(result => {
                _this.userList = result.data || [];
            }).catch(() => {
            });
        },
        //获取资源树
        initResourceTree() {
            const _this = this;
            let queryData = { parentId: '-1' };
            sysResourceApi.findSysResourceTree(queryData, result => {
                _this.resourceZTreeData = sysResourceApi.transferRoleZTreeData(result.data);
                // 获取叶子节点，即下级菜单为空的数据
                let allList = sysResourceApi.transferZTreeData(result.data);
                let leafResourceList = [];
                let filterMenus = allList.filter(item => item.res_type === 'menu');
                filterMenus.forEach(item => {
                    let filterBtns = allList.filter(child => child.pId === item.id);
                    if (_this.$utils.isNotEmptyList(filterBtns)) {
                        leafResourceList = leafResourceList.concat(filterBtns);
                    } else {
                        leafResourceList.push(item);
                    }
                });
                _this.leafResourceList = leafResourceList;
                _this.initRoleResourse(_this.propsData.resource_list);
            });
        },
        initRoleResourse(resource_list) {
            const _this = this;
            if (!resource_list) {
                resource_list = [];
            }
            _this.selectTreeData = [];
            if (_this.$refs.roleTree) {
                let checkTree = _this.$refs.roleTree.$refs.checkTree;
                let leafList = _this.leafResourceList.map(item => item.id);
                let filterLeafList = resource_list.filter(item => leafList.indexOf(item) !== -1);
                checkTree.setCheckedKeys(filterLeafList);
            }
        },
        handleTreeEvent(event) {
            this.selectTreeData = event.ref.getCheckedNodes();
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('roleForm');
            if (valid) {
                let checkTree = _this.$refs.roleTree.$refs.checkTree;
                let subData = $.extend({}, _this.formData);
                _this.selectTreeData = checkTree.getCheckedNodes();
                let half = checkTree.getHalfCheckedNodes();
                if (_this.selectTreeData.length > 0) {
                    subData.resourceList = _this.selectTreeData.map(item => {
                        return {
                            role_sid: _this.formData.sid,
                            resource_sid: item.id,
                            check_type: 1
                        }
                    })
                }
                if (half.length > 0) {
                    let half_resourceList = half.map(item => {
                        return {
                            role_sid: _this.formData.sid,
                            resource_sid: item.id,
                            check_type: 0
                        }
                    })
                    subData.resourceList = subData.resourceList.concat(half_resourceList);
                }
                return _this.fetchData(_this.$api.API_SaveSysRole, subData).then(() => {
                    _this.$message.success('保存成功！');
                    return true;
                }).catch(() => {
                    return false;
                });
            }
            return valid;
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.role_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
